/*
 * Swinney_CPE301_Design2.c
 *
 * Created: 3/4/2014 10:27:12 PM
 *  Author: Justin
 */ 


#include <stdio.h> // provides sprintf()
#include <string.h> // provides strcat()
#include <avr/interrupt.h> //provides files/commands for interrupts
#include <avr/io.h> // all AVR programs use this
#include <avr/pgmspace.h> // provides pgm_read_byte()
char int0_falledge_cnt; //incremented when 10th falling edge occurs

int main()
{
	EICRA = 0x0A; //sets ISC01 & ISC02 to 10; falling edge generates interrupt
	EIMSK = 0x03; //sets int1 and int0 to 10; inital values 0, external pin inter is enabled
	sei(); //sets the global interrupts
	DDRB = 0XFF; //sets all of portb to output
	OCR1AH = 0X20; //count to 8192 which is 1/8 the time to count to 2^16 bits (2^13)
	OCR1AL = 0x00; //lower bits of 2^13
	TCCR1A = 0x40; //CTC mode, 256 prescalar, toggle OC1A, loads the settings
	TCCR1B = 0x0C;	//CTC mode, 256 prescalar, toggle OC1A
	
	//to count every falling edge using timer0
    DDRD = 0xE3; // pin 2,3,4 input & remaining pins output
	DDRC = 0xFF; // sets all of port c to output
	TCCR0A = 0x00; // timer0 clocked on falling edge of timer1
	TCCR0B = 0x06; // timer0 clocked on falling edge of timer1
	while(1) //loop that doesn't end
    {		
		PORTD = TCNT0; //send the count to portc (PC0-PC5)
		PORTC = TCNT0; //send the same count to portd(PD6-PD7)
		if (TIFR1 == 0x02) //checking if the 1-bit in tifr register is 1
		{
			TIFR1 = 0xFF; //Clears the compare flag by adding a logic 1
			TCNT1H = 0x00; //clear the counter
			TCNT1L = 0x00; //clears the counter
		}
    }
return 0; //return for main
}

ISR (INT1_vect) //interrupt on int1 vector
{
	char count; // Falling Edge Counter
	count = TCNT0; //loads the value of # of falling edges
	if (count %10 == 0) // checks for 10th falling edge
	{
		PORTB ^= (1<<6); //toggles pin by adding a logic "1"
	}
}
ISR (INT0_vect) //interrupt on int0 vector 
{ 
	int0_falledge_cnt ++; //Counts for timer 1 reset 
	if (int0_falledge_cnt %2 == 0) //checks for 2nd falling edge of timer 1 reset
	{
		PORTB ^= (1<<7); //toggles pin by adding a logic "1"
		int0_falledge_cnt = 0; //resets count
	}
}